<template>
  <view class="circles-container">
    <!-- 自定义导航栏 -->
    <view class="custom-navbar" :style="{ paddingTop: statusBarHeight + 'px' }">
      <view class="navbar-content">
        <view class="navbar-left">
          <text class="navbar-title">圈子广场</text>
        </view>
        <view class="navbar-right">
          <view class="search-btn" @click="handleSearch">
            <u-icon name="search" color="white" size="20"></u-icon>
          </view>
          <view class="create-btn" @click="handleCreateCircle">
            <u-icon name="plus" color="white" size="20"></u-icon>
          </view>
        </view>
      </view>
    </view>

    <!-- 主要内容区域 -->
    <scroll-view
      class="main-content"
      scroll-y
      @scrolltolower="loadMore"
      :refresher-enabled="true"
      :refresher-triggered="refreshing"
      @refresherrefresh="onRefresh"
    >
      <!-- 分类筛选区域 -->
      <view class="category-filter">
        <scroll-view class="filter-scroll" scroll-x>
          <view class="filter-list">
            <view
              class="filter-item"
              :class="{ active: selectedCategory === item.cate_id }"
              v-for="item in categoryList"
              :key="item.cate_id"
              @click="selectCategory(item)"
            >
              <text class="filter-text">{{ item.cate_name }}</text>
            </view>
          </view>
        </scroll-view>
      </view>

      <!-- 排序和筛选 -->
      <view class="sort-filter">
        <view class="sort-tabs">
          <text
            class="sort-tab"
            :class="{ active: currentSort === 'hot' }"
            @click="changeSort('hot')"
          >热门</text>
          <text
            class="sort-tab"
            :class="{ active: currentSort === 'latest' }"
            @click="changeSort('latest')"
          >最新</text>
          <text
            class="sort-tab"
            :class="{ active: currentSort === 'members' }"
            @click="changeSort('members')"
          >人气</text>
        </view>
        <view class="filter-btn" @click="showFilterModal = true">
          <u-icon name="options" color="#667eea" size="18"></u-icon>
          <text class="filter-text">筛选</text>
        </view>
      </view>

      <!-- 推荐圈子横幅 -->
      <view class="recommend-banner" v-if="recommendCircles.length > 0">
        <view class="banner-header">
          <text class="banner-title">推荐圈子</text>
          <text class="banner-subtitle">发现更多有趣的圈子</text>
        </view>
        <scroll-view class="recommend-scroll" scroll-x>
          <view class="recommend-list">
            <view
              class="recommend-item glass-card"
              v-for="item in recommendCircles"
              :key="item.id"
              @click="handleCircleDetail(item)"
            >
              <image :src="item.cover_image" class="recommend-image" mode="aspectFill"></image>
              <view class="recommend-info">
                <text class="recommend-name">{{ item.cate_name }}</text>
                <text class="recommend-desc">{{ item.description }}</text>
                <view class="recommend-stats">
                  <text class="stat-text">{{ item.member_count }}人</text>
                </view>
              </view>
            </view>
          </view>
        </scroll-view>
      </view>

      <!-- 圈子列表 -->
      <view class="circles-list">
        <view
          class="circle-item modern-card"
          v-for="item in circleList"
          :key="item.id"
          @click="handleCircleDetail(item)"
        >
          <!-- 圈子封面 -->
          <view class="circle-cover">
            <image :src="item.cover_image" class="cover-image" mode="aspectFill"></image>
            <view class="cover-overlay">
              <view class="circle-badge" v-if="item.is_official">
                <u-icon name="checkmark-circle-fill" color="#4CAF50" size="16"></u-icon>
                <text class="badge-text">官方</text>
              </view>
              <view class="circle-badge hot" v-if="item.is_hot">
                <u-icon name="fire-fill" color="#FF6B35" size="16"></u-icon>
                <text class="badge-text">热门</text>
              </view>
            </view>
          </view>

          <!-- 圈子信息 -->
          <view class="circle-info">
            <view class="circle-header">
              <text class="circle-name">{{ item.cate_name }}</text>
              <view class="join-status">
                <u-button
                  v-if="!item.isJoined"
                  size="mini"
                  type="primary"
                  :custom-style="{ background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', border: 'none' }"
                  @click.stop="handleJoinCircle(item)"
                >
                  {{ item.join_type === 1 ? '申请加入' : '立即加入' }}
                </u-button>
                <u-button
                  v-else
                  size="mini"
                  type="info"
                  plain
                  @click.stop="handleLeaveCircle(item)"
                >
                  已加入
                </u-button>
              </view>
            </view>

            <text class="circle-desc">{{ item.description || '暂无描述' }}</text>

            <!-- 圈子统计 -->
            <view class="circle-stats">
              <view class="stat-item">
                <u-icon name="account-fill" color="#999" size="14"></u-icon>
                <text class="stat-text">{{ item.member_count || 0 }}成员</text>
              </view>
              <view class="stat-item">
                <u-icon name="chat-fill" color="#999" size="14"></u-icon>
                <text class="stat-text">{{ item.post_count || 0 }}帖子</text>
              </view>
              <view class="stat-item">
                <u-icon name="time-fill" color="#999" size="14"></u-icon>
                <text class="stat-text">{{ formatTime(item.create_time) }}</text>
              </view>
            </view>

            <!-- 最新动态预览 -->
            <view class="latest-posts" v-if="item.latestPosts && item.latestPosts.length > 0">
              <text class="latest-title">最新动态</text>
              <view class="post-preview">
                <text class="preview-text">{{ item.latestPosts[0].content }}</text>
              </view>
            </view>

            <!-- 成员头像 -->
            <view class="member-avatars" v-if="item.memberAvatars && item.memberAvatars.length > 0">
              <text class="members-title">活跃成员</text>
              <view class="avatars-list">
                <u-avatar
                  v-for="(avatar, index) in item.memberAvatars.slice(0, 5)"
                  :key="index"
                  :src="avatar"
                  size="24"
                  class="member-avatar"
                ></u-avatar>
                <text class="more-members" v-if="item.member_count > 5">+{{ item.member_count - 5 }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 加载更多 -->
      <view class="load-more" v-if="hasMore">
        <u-loading-icon v-if="loading" color="#667eea" size="20"></u-loading-icon>
        <text class="load-text">{{ loading ? '加载中...' : '上拉加载更多' }}</text>
      </view>

      <!-- 没有更多数据 -->
      <view class="no-more" v-if="!hasMore && circleList.length > 0">
        <text class="no-more-text">没有更多圈子了</text>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="!loading && circleList.length === 0">
        <u-icon name="inbox" color="#ccc" size="60"></u-icon>
        <text class="empty-text">暂无圈子</text>
        <u-button
          type="primary"
          :custom-style="{ background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', border: 'none', marginTop: '20px' }"
          @click="handleCreateCircle"
        >
          创建第一个圈子
        </u-button>
      </view>
    </scroll-view>

    <!-- 筛选弹窗 -->
    <u-popup v-model="showFilterModal" mode="bottom" border-radius="20">
      <view class="filter-modal">
        <view class="modal-header">
          <text class="modal-title">筛选条件</text>
          <u-icon name="close" color="#999" size="20" @click="showFilterModal = false"></u-icon>
        </view>

        <view class="filter-section">
          <text class="section-title">圈子类型</text>
          <view class="filter-options">
            <view
              class="option-item"
              :class="{ active: filterOptions.type === item.value }"
              v-for="item in typeOptions"
              :key="item.value"
              @click="filterOptions.type = item.value"
            >
              <text class="option-text">{{ item.label }}</text>
            </view>
          </view>
        </view>

        <view class="filter-section">
          <text class="section-title">成员规模</text>
          <view class="filter-options">
            <view
              class="option-item"
              :class="{ active: filterOptions.memberRange === item.value }"
              v-for="item in memberRangeOptions"
              :key="item.value"
              @click="filterOptions.memberRange = item.value"
            >
              <text class="option-text">{{ item.label }}</text>
            </view>
          </view>
        </view>

        <view class="modal-footer">
          <u-button
            type="info"
            plain
            @click="resetFilter"
            :custom-style="{ flex: 1, marginRight: '10px' }"
          >
            重置
          </u-button>
          <u-button
            type="primary"
            :custom-style="{ flex: 1, background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)', border: 'none' }"
            @click="applyFilter"
          >
            确定
          </u-button>
        </view>
      </view>
    </u-popup>

  </view>
</template>

<script>
export default {
  data() {
    return {
      statusBarHeight: 0,
      refreshing: false,
      loading: false,
      hasMore: true,
      selectedCategory: 0,
      currentSort: 'hot',
      page: 1,
      pageSize: 10,
      showFilterModal: false,

      // 筛选选项
      filterOptions: {
        type: 'all',
        memberRange: 'all'
      },

      typeOptions: [
        { label: '全部', value: 'all' },
        { label: '官方圈子', value: 'official' },
        { label: '用户圈子', value: 'user' },
        { label: '热门圈子', value: 'hot' }
      ],

      memberRangeOptions: [
        { label: '全部', value: 'all' },
        { label: '100人以下', value: 'small' },
        { label: '100-1000人', value: 'medium' },
        { label: '1000人以上', value: 'large' }
      ],

      // 分类列表
      categoryList: [
        { cate_id: 0, cate_name: '全部' }
      ],

      // 推荐圈子
      recommendCircles: [],

      // 圈子列表
      circleList: []
    }
  },

  onLoad() {
    this.initPage()
  },

  onShow() {
    this.loadData()
  },

  methods: {
    // 初始化页面
    async initPage() {
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight || 0

      await this.loadCategories()
      await this.loadRecommendCircles()
      await this.loadCircles()
    },

    // 加载数据
    async loadData() {
      this.refreshing = true
      this.page = 1
      this.circleList = []
      await this.loadCircles()
      this.refreshing = false
    },

    // 下拉刷新
    async onRefresh() {
      await this.loadData()
    },

    // 加载更多
    async loadMore() {
      if (this.loading || !this.hasMore) return

      this.page++
      await this.loadCircles()
    },

    // 加载分类
    async loadCategories() {
      try {
        // 模拟数据
        const mockCategories = [
          { cate_id: 1, cate_name: '校园生活' },
          { cate_id: 2, cate_name: '兴趣爱好' },
          { cate_id: 3, cate_name: '学习交流' },
          { cate_id: 4, cate_name: '运动健身' },
          { cate_id: 5, cate_name: '美食分享' },
          { cate_id: 6, cate_name: '旅行摄影' }
        ]

        this.categoryList = [this.categoryList[0], ...mockCategories]
      } catch (error) {
        console.error('加载分类失败:', error)
      }
    },

    // 加载推荐圈子
    async loadRecommendCircles() {
      try {
        // 模拟数据
        this.recommendCircles = [
          {
            id: 1,
            cate_name: '校园摄影',
            description: '分享校园美景',
            cover_image: 'https://cdn.uviewui.com/uview/album/1.jpg',
            member_count: 1234
          },
          {
            id: 2,
            cate_name: '编程学习',
            description: '一起学编程',
            cover_image: 'https://cdn.uviewui.com/uview/album/2.jpg',
            member_count: 856
          },
          {
            id: 3,
            cate_name: '美食探店',
            description: '发现美味',
            cover_image: 'https://cdn.uviewui.com/uview/album/3.jpg',
            member_count: 2341
          }
        ]
      } catch (error) {
        console.error('加载推荐圈子失败:', error)
      }
    },

    // 加载圈子列表
    async loadCircles() {
      if (this.loading) return

      this.loading = true

      try {
        // 模拟数据
        const mockCircles = this.generateMockCircles()

        if (this.page === 1) {
          this.circleList = mockCircles
        } else {
          this.circleList.push(...mockCircles)
        }

        this.hasMore = mockCircles.length === this.pageSize
      } catch (error) {
        console.error('加载圈子失败:', error)
        this.showToast('加载失败，请重试', 'error')
      } finally {
        this.loading = false
      }
    },

    // 生成模拟圈子数据
    generateMockCircles() {
      const circles = []
      const names = ['校园生活', '编程技术', '摄影爱好', '音乐分享', '运动健身', '美食探店', '旅行日记', '读书笔记', '电影讨论', '游戏交流']
      const descriptions = [
        '分享校园生活的点点滴滴',
        '一起学习编程技术，共同进步',
        '用镜头记录美好瞬间',
        '分享喜欢的音乐，交流音乐心得',
        '健康生活，运动打卡',
        '发现城市美食，分享用餐体验',
        '记录旅行足迹，分享旅行攻略',
        '好书推荐，读书心得分享',
        '讨论热门电影，分享观影感受',
        '游戏攻略分享，组队开黑'
      ]

      for (let i = 0; i < this.pageSize; i++) {
        const circle = {
          id: Date.now() + i,
          cate_name: names[i % names.length],
          description: descriptions[i % descriptions.length],
          cover_image: `https://cdn.uviewui.com/uview/album/${(i % 6) + 1}.jpg`,
          member_count: Math.floor(Math.random() * 5000) + 100,
          post_count: Math.floor(Math.random() * 1000) + 50,
          create_time: new Date(Date.now() - Math.random() * 86400000 * 30).toISOString(),
          is_official: Math.random() > 0.8,
          is_hot: Math.random() > 0.7,
          join_type: Math.random() > 0.3 ? 0 : 1, // 0: 直接加入, 1: 申请加入
          isJoined: Math.random() > 0.6,
          latestPosts: [
            { content: '今天天气真好，适合出去走走' }
          ],
          memberAvatars: [
            'https://cdn.uviewui.com/uview/album/1.jpg',
            'https://cdn.uviewui.com/uview/album/2.jpg',
            'https://cdn.uviewui.com/uview/album/3.jpg'
          ]
        }
        circles.push(circle)
      }

      return circles
    },

    // 选择分类
    selectCategory(category) {
      this.selectedCategory = category.cate_id
      this.loadData()
    },

    // 切换排序
    changeSort(sort) {
      this.currentSort = sort
      this.loadData()
    },

    // 应用筛选
    applyFilter() {
      this.showFilterModal = false
      this.loadData()
    },

    // 重置筛选
    resetFilter() {
      this.filterOptions = {
        type: 'all',
        memberRange: 'all'
      }
    },

    // 格式化时间
    formatTime(timeStr) {
      const time = new Date(timeStr)
      const now = new Date()
      const diff = now - time

      if (diff < 86400000) return '今天创建'
      if (diff < 604800000) return Math.floor(diff / 86400000) + '天前'
      if (diff < 2592000000) return Math.floor(diff / 604800000) + '周前'

      return Math.floor(diff / 2592000000) + '月前'
    },

    // 事件处理
    handleSearch() {
      this.$tab.navigateTo('/pages/search/circles')
    },

    handleCreateCircle() {
      this.$tab.navigateTo('/pages/circles/create')
    },

    handleCircleDetail(circle) {
      this.$tab.navigateTo(`/pages/circles/detail?id=${circle.id}`)
    },

    async handleJoinCircle(circle) {
      try {
        // 这里应该调用API加入圈子
        circle.isJoined = true
        circle.member_count++

        this.showToast(circle.join_type === 1 ? '申请已提交' : '加入成功', 'success')
      } catch (error) {
        this.showToast('操作失败，请重试', 'error')
      }
    },

    async handleLeaveCircle(circle) {
      try {
        const res = await uni.showModal({
          title: '确认退出',
          content: `确定要退出"${circle.cate_name}"圈子吗？`
        })

        if (res.confirm) {
          // 这里应该调用API退出圈子
          circle.isJoined = false
          circle.member_count--

          this.showToast('已退出圈子', 'success')
        }
      } catch (error) {
        this.showToast('操作失败，请重试', 'error')
      }
    },

    showToast(title, type = 'default') {
      // 使用 uView 2.0 的 toast 方法
      this.$u.toast(title)
    }
  }
}
</script>

<style lang="scss" scoped>
.circles-container {
  min-height: 100vh;
  background: #f8f9fa;
}

.custom-navbar {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  z-index: 999;

  .navbar-content {
    height: 44px;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 15px;

    .navbar-title {
      font-size: 18px;
      font-weight: 600;
      color: white;
    }

    .navbar-right {
      display: flex;
      align-items: center;
      gap: 15px;

      .search-btn, .create-btn {
        width: 36px;
        height: 36px;
        border-radius: 18px;
        background: rgba(255, 255, 255, 0.2);
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
}

.main-content {

  height: calc(100vh - 88px);
}

.category-filter {
  background: white;
  padding: 15px 0;
  margin-bottom: 10px;

  .filter-scroll {
    white-space: nowrap;

    .filter-list {
      display: flex;
      padding: 0 15px;
      gap: 15px;

      .filter-item {
        padding: 8px 16px;
        border-radius: 20px;
        background: #f5f5f5;
        white-space: nowrap;

        &.active {
          background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);

          .filter-text {
            color: white;
          }
        }

        .filter-text {
          font-size: 14px;
          color: #666;
        }
      }
    }
  }
}

.sort-filter {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background: white;
  margin-bottom: 10px;

  .sort-tabs {
    display: flex;
    gap: 20px;

    .sort-tab {
      font-size: 14px;
      color: #999;
      padding: 5px 0;

      &.active {
        color: #667eea;
        font-weight: 600;
        border-bottom: 2px solid #667eea;
      }
    }
  }

  .filter-btn {
    display: flex;
    align-items: center;
    gap: 5px;

    .filter-text {
      font-size: 14px;
      color: #667eea;
    }
  }
}

.recommend-banner {
  background: white;
  margin-bottom: 10px;
  padding: 15px;

  .banner-header {
    margin-bottom: 15px;

    .banner-title {
      font-size: 16px;
      font-weight: 600;
      color: #333;
      display: block;
      margin-bottom: 5px;
    }

    .banner-subtitle {
      font-size: 12px;
      color: #999;
    }
  }

  .recommend-scroll {
    white-space: nowrap;

    .recommend-list {
      display: flex;
      gap: 15px;

      .recommend-item {
        min-width: 200px;
        padding: 15px;

        .recommend-image {
          width: 100%;
          height: 80px;
          border-radius: 8px;
          margin-bottom: 10px;
        }

        .recommend-info {
          .recommend-name {
            font-size: 14px;
            font-weight: 600;
            color: #333;
            display: block;
            margin-bottom: 5px;
          }

          .recommend-desc {
            font-size: 12px;
            color: #999;
            display: block;
            margin-bottom: 8px;
          }

          .recommend-stats {
            .stat-text {
              font-size: 12px;
              color: #667eea;
            }
          }
        }
      }
    }
  }
}

.circles-list {
  .circle-item {
    margin: 0 15px 15px;
    overflow: hidden;

    .circle-cover {
      position: relative;
      height: 120px;

      .cover-image {
        width: 100%;
        height: 100%;
      }

      .cover-overlay {
        position: absolute;
        top: 10px;
        right: 10px;
        display: flex;
        gap: 8px;

        .circle-badge {
          display: flex;
          align-items: center;
          gap: 4px;
          padding: 4px 8px;
          border-radius: 12px;
          background: rgba(255, 255, 255, 0.9);

          &.hot {
            background: rgba(255, 107, 53, 0.9);

            .badge-text {
              color: white;
            }
          }

          .badge-text {
            font-size: 10px;
            color: #333;
          }
        }
      }
    }

    .circle-info {
      padding: 15px;

      .circle-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 8px;

        .circle-name {
          font-size: 16px;
          font-weight: 600;
          color: #333;
        }
      }

      .circle-desc {
        font-size: 14px;
        color: #666;
        line-height: 1.4;
        margin-bottom: 12px;
        display: block;
      }

      .circle-stats {
        display: flex;
        gap: 15px;
        margin-bottom: 12px;

        .stat-item {
          display: flex;
          align-items: center;
          gap: 4px;

          .stat-text {
            font-size: 12px;
            color: #999;
          }
        }
      }

      .latest-posts {
        margin-bottom: 12px;

        .latest-title {
          font-size: 12px;
          color: #999;
          display: block;
          margin-bottom: 5px;
        }

        .post-preview {
          background: #f8f9fa;
          padding: 8px 12px;
          border-radius: 8px;

          .preview-text {
            font-size: 12px;
            color: #666;
          }
        }
      }

      .member-avatars {
        .members-title {
          font-size: 12px;
          color: #999;
          display: block;
          margin-bottom: 8px;
        }

        .avatars-list {
          display: flex;
          align-items: center;
          gap: 5px;

          .member-avatar {
            border: 2px solid white;
          }

          .more-members {
            font-size: 12px;
            color: #999;
            margin-left: 5px;
          }
        }
      }
    }
  }
}

.load-more, .no-more {
  text-align: center;
  padding: 20px;

  .load-text, .no-more-text {
    font-size: 14px;
    color: #999;
  }
}

.empty-state {
  text-align: center;
  padding: 60px 20px;

  .empty-text {
    font-size: 16px;
    color: #999;
    margin-top: 20px;
    display: block;
  }
}

.filter-modal {
  padding: 20px;

  .modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    .modal-title {
      font-size: 18px;
      font-weight: 600;
      color: #333;
    }
  }

  .filter-section {
    margin-bottom: 20px;

    .section-title {
      font-size: 14px;
      font-weight: 600;
      color: #333;
      margin-bottom: 10px;
      display: block;
    }

    .filter-options {
      display: flex;
      flex-wrap: wrap;
      gap: 10px;

      .option-item {
        padding: 8px 16px;
        border-radius: 20px;
        background: #f5f5f5;
        border: 1px solid transparent;

        &.active {
          background: rgba(102, 126, 234, 0.1);
          border-color: #667eea;

          .option-text {
            color: #667eea;
          }
        }

        .option-text {
          font-size: 14px;
          color: #666;
        }
      }
    }
  }

  .modal-footer {
    display: flex;
    gap: 10px;
    margin-top: 30px;
  }
}
</style>
